<template>
  <!-- 借出出库 -->
  <div>
    <!-- 搜索框 -->
    <TopFilter ref="form" :list="form" :cols="4" :labelWidth="'85'" :collapse="false" :isSubmitBtn="false" />
    <ButtonArea style="padding-left:85px;">
      <el-button size="small" type="primary" :disabled="buildBtn" @click="newBuild">新建</el-button>
      <el-button size="small" type="primary" :disabled="saveBtn" @click="save">保存</el-button>
      <el-button size="small" type="primary" :disabled="chukuBtn" :loading="outBtnLoading" @click="out">出库</el-button>
      <el-button size="small" type="primary" :disabled="cancelBtn" @click="cancel">取消</el-button>
      <el-button size="small" type="primary" icon="el-icon-printer" :disabled="printBtn" @click="handlePrint">打印</el-button>
      <el-button size="small" type="primary" :disabled="zuofeiBtn" :loading="quitBtnLoading" @click="quit">作废</el-button>
    </ButtonArea>
    <!-- 列表展示 -->
    <FilterTable
      ref="table"
      :dataSource="tableDataList"
      columnsRef="partPartOutboundAdjustOutboundIndex"
      :columns="columns"
      :selectionType="'single'"
      :onSyncTableData="handleTableDataUpdate"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectTableFun"
    >
      <template slot="moreActions">
        <span @click="() => handleDelete()">删除数据</span>
        <!-- <el-button :disabled="this.isFinished" @click="deleteHandle()">删 除</el-button> -->
      </template>
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" :disabled="addBtn" @click="addHandle">新增</el-button>
        <el-button size="small" type="primary" icon="el-icon-download" :disabled="exportBtn" @click="importFun">导出</el-button>
      </template>
    </FilterTable>

    <!-- 借出出库单选择 -->
    <BaseDialog :visible.sync="visibleAdjustOrder" title="借出出库单选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <adjustOrder :ptype="ptype" :orderList="orderList" @close="visibleAdjustOrder = false" @saveDialog="handleOrderSelectConfirm" />
    </BaseDialog>
    <!-- 借出出库编辑 -->
    <BaseDialog :visible.sync="visibleAdjustOutboundEdit" title="借出出库编辑" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <adjustOutboundEdit :type="handleType" :rowData="formData" @close="visibleAdjustOutboundEdit = false" />
    </BaseDialog>
    <!-- 客户选择 -->
    <BaseDialog :visible.sync="visibleCustomerChoice" title="客户选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <customerChoice :type="handleType" :rowData="formData" @addCustomerCode="handleCustomerChoiceConfirm" @close="visibleCustomerChoice = false" />
    </BaseDialog>
    <!-- 借出出库配件新增 -->
    <Drawer
      :visible.sync="visibleAdjustOrderAdd"
      :title="'借出出库配件' + (adjustOrderAddEditMode ? '编辑' : '新增')"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <adjustOrderAdd
        :editMode="adjustOrderAddEditMode"
        :editData="editData"
        :billNo="BILL_NO"
        :tax="tax"
        :priceRate="customerPriceRate"
        @close="visibleAdjustOrderAdd = false"
        @onConfirm="handlePartAddConfirm"
        @handlePartAddConfirmEdit="handlePartAddConfirmEdit"
        @reSearchTableData="getMainTableList"
      />
    </Drawer>
    <!-- 对应单号选择弹窗 -->
    <BaseDialog title="对应单选择" :visible.sync="visibleBillNo" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <billNo :rowData="inTableListData" :billNo="BILL_NO" @onConfirm="handleBillNoConfirm" @close="visibleBillNo = false" />
    </BaseDialog>
    <!-- 打印 -->
    <div v-if="dy">
      <BasePrint
        ref="print"
        :data="SalesprintList"
        :printerType="printParams.vPrintType ? (printParams.vPrintType == 99901002 ? 'stylus' : 'laser') : 'stylus'"
        :alwaysPrint="printParams.vPageType ? (printParams.vPageType == 99911002 ? true : false) : true"
        :printCopies="printParams.nPages || 1"
        :direction="printParams.vPageDirection == 99921001 ? 'horizontal' : 'vertical'"
        :directPrint="printParams.vDirectPrint ? (printParams.vDirectPrint == 1 ? true : false) : true"
        :isDuplex="printParams.vBothPrint == 1 ? true : false"
        template="templateAdjustOutbound"
      />
    </div>
  </div>
</template>

<script>
import { isAuthorized, confirmAction } from '@/utils/index'; // 权限
import { getStorageList, queryMainTableByNo, saveOutboundOrderCreate, outBoundOrderRecorded, outBoundOrderDelete, partAllocateOutExportExcel } from '@/api/part/partOutbound/adjustOutbound';
import { searchAdjustOrder, printData } from '@/api/part/partOutbound/adjustOutbound/index';
import { formatdate, jsonToHump, notifyAction, exportExcelFile } from '@/utils';
import { dictionary } from '@/utils/dictMixin';
import AdjustOrder from './adjustOrder';
import AdjustOutboundEdit from './adjustOutboundEdit';
import { findAllRepair } from '@/api/repair/basicParameters';
// import CustomerChoice from './customerChoice';
import CustomerChoice from '@/pages/part/partInventory/adjustInventory/searchCustomerPage.vue';
import AdjustOrderAdd from './adjustOrderAdd';
import moment from 'moment';
import { getDealerUser } from '@/api/part/partInventory/partInventory/index.js';
import billNo from './billNo';
import { dealerPrintApi } from '@/api/repair/index.js';
import { queryTex } from '@/api/part/common';

export default {
  name: 'Adjust',
  components: {
    AdjustOrder,
    AdjustOutboundEdit,
    CustomerChoice,
    AdjustOrderAdd,
    billNo
  },
  mixins: [dictionary],
  data() {
    return {
      inTableListData: [], // 初始化数据
      BILL_NO: '', // 对应单号单号
      visibleBillNo: false, // 借入入库单号选择
      cunUserList: [], // 存所有人的数组
      cunId: '', // 存单号的id
      cunPrintlist: [],
      SalesprintList: {},
      dy: false,
      shanchu: [],
      orderList: '',
      customerPriceRate: 1,
      // <!--控制操作的按钮-->
      handleDeletebtn: null,
      editHandlebtn: null,
      isFinished: false,
      // <!--table的按钮-->
      addBtn: true,
      exportBtn: true,
      buildBtn: false,
      chukuBtn: true,
      outBtn: true, // 作废
      cancelBtn: true, // 取消
      printBtn: true, // 打印 原true
      // quitBtn: true, //作废
      tax: 0.13,
      form: this.createForm(),
      columns: this.createTableColumns(),
      // fetchApi: {},
      fetchParams: {},
      zuofeiBtn: true,
      saveBtn: true,
      visibleAdjustOrder: false,
      visibleAdjustOutboundEdit: false,
      visibleCustomerChoice: false,
      visibleAdjustOrderAdd: false,
      adjustOrderAddEditMode: false, // 添加弹窗编辑模式
      outBtnLoading: false, // 出库按钮加载状态
      quitBtnLoading: false, // 作废按钮加载状态
      formData: {},
      handleType: '',
      tableDataList: [], // table数据集合(添加数据与清空数据使用)
      tableDataBackUp: [], // table数据(获取用)
      editData: {}, // 编辑的行数据
      selectRow: null,
      printParams: {} // 打印参数
    };
  },
  computed: {
    ptype() {
      return this.$route.meta.ptype;
    }, // 模块区分
    billNo() {
      return this.form.find(item => item.fieldName == 'allocateType').initialValue;
    }
  },
  watch: {
    billNo(newVal, oldVal) {
      let res = newVal == '82121003';
      this.form.find(item => item.fieldName == 'allocateInNo').disabled = res;
      // 判断添加配件按钮可点击
      if (this.buildBtn) {
        this.addBtn = !res;
      }
    }
    // buildBtn(newVal, oldVal) {
    //   if (!newVal) {
    //     let temp = this.form.find(item => item.fieldName == 'allocateInNo').disabled;
    //     // console.log(temp, 'slsllal');
    //     this.addBtn = !temp;
    //   }
    //   this.form.find(item => item.fieldName == 'allocateType').disabled = !newVal;
    // }
  },
  created() {
    this.getDealerUser();
    this.getSrorageList();
    // this.findAllRepair();
    this.querySysTex();
    this.queryPrintParams();
  },
  methods: {
    // 获取税率
    async querySysTex() {
      let res = await queryTex();
      this.tax = res.data;
    },
    // 对应单号选择点击
    billNoHandle() {
      this.BILL_NO = this.form.find(item => item.fieldName == 'allocateInNo').initialValue;
      this.visibleBillNo = true;
    },
    // 对应单号弹窗确定按钮
    handleBillNoConfirm(val) {
      this.form.find(item => item.fieldName == 'allocateInNo').initialValue = val[0].ALLOCATE_IN_NO;
      // 客户名称
      let customerName = this.form.find(item => item.fieldName == 'customerName').initialValue;
      // 如果选择了则不进行赋值
      this.form.find(item => item.fieldName == 'customerName').initialValue = customerName ? customerName : val[0].CUSTOMER_NAME;
      // 客户代码
      let customerCode = this.form.find(item => item.fieldName == 'customerCode').initialValue;
      // 如果选择了则不进行赋值
      this.form.find(item => item.fieldName == 'customerCode').initialValue = customerCode ? customerCode : val[0].CUSTOMER_CODE;
      this.saveBtn = false;
      // 保存为fasle
      this.saveBtn = false;
      this.chukuBtn = true;
      this.form.find(item => item.fieldName == 'allocateInNo').disabled = true;
      this.form.find(item => item.fieldName == 'allocateType').disabled = true;
      this.$refs.table.EXECUTE_INSERT(val);
      // this.visibleBillNo = false;
    },
    createForm() {
      return [
        {
          type: 'INPUT',
          label: '借出出库单号',
          fieldName: 'adjustOutboundNo',
          initialValue: null,
          disabled: false,
          unitRender: props => {
            return <el-button icon="el-icon-search" onClick={this.adjustOutbound}></el-button>;
          },
          onEnter: val => {
            this.adjustOutbound();
          }
        },
        {
          type: 'INPUT',
          label: '客户代码',
          fieldName: 'customerCode',
          initialValue: null,
          rules: [{ required: true, message: '请输入客户代码', trigger: 'blur' }],
          disabled: true,
          unitRender: props => {
            return <el-button icon="el-icon-search" onClick={this.order}></el-button>;
          },
          onEnter: val => {
            // this.search_order = val;
            this.order();
          }
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'customerName',
          initialValue: '',
          disabled: false,
          itemList: []
        },
        {
          type: 'INPUT',
          label: '出库日期',
          fieldName: 'outBoundDate',
          initialValue: '',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark',
          initialValue: '',
          disabled: false
        },
        {
          type: 'RADIO',
          label: '类型区分',
          fieldName: 'allocateType',
          initialValue: '82121003',
          disabled: true,
          itemList: [
            { text: '借出出库', value: '82121003' },
            { text: '还出出库', value: '82121004' }
          ],
          placeholder: ''
          // rules: [{ required: true, message: '请选择出库日期', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '借进单号',
          fieldName: 'allocateInNo',
          placeholder: '请选择...',
          disabled: true,
          unitRender: props => {
            return <el-button icon="el-icon-search" onClick={() => this.billNoHandle()}></el-button>;
          }
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 60,
          fixed: 'left',
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" disabled={this.isFinished} onClick={() => this.editHandle(props.row)}>
                  编辑
                </el-button>
              </div>
            );
          }
        },
        {
          title: '仓库',
          dataIndex: 'STORAGE_CODE',
          width: 150,
          sorter: true,
          editable: true,
          editType: 'select',
          editItems: [],
          editRequired: false,
          disabled: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: []
        },
        // {
        //   title: '仓库代码',
        //   dataIndex: 'STORAGE_CODE',
        //   width: 150,
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          width: 150,
          sorter: true,
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          width: 150,
          sorter: true,
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '单位',
          dataIndex: 'UNIT_NAME',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '是否3C免办',
          dataIndex: 'IS_EXEMPT_C',
          width: 150,
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: this.createDictList('1004'),
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004')
        },
        {
          title: '出库数量',
          dataIndex: 'OUT_QUANTITY',
          width: 150,
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '出库单价',
          dataIndex: 'OUT_PRICE',
          width: 150,
          sorter: true,
          filter: true,
          precision: 2,
          // summation: true
          filterType: 'number'
        },
        {
          title: '不含税单价',
          dataIndex: 'COST_OUT_PRICE',
          width: 150,
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          render: props => {
            return <span>{(props.row.OUT_PRICE / (1 * 1 + this.tax * 1)).toFixed(2)}</span>; // 对结果进行处理
          }
        },
        {
          title: '出库金额',
          dataIndex: 'OUT_AMOUNT',
          width: 150,
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '不含税金额',
          dataIndex: 'tax_freeAmount',
          width: 150,
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number',
          render: props => {
            return <span>{(props.row.OUT_AMOUNT / (1 * 1 + this.tax * 1)).toFixed(2)}</span>; // 对结果进行处理
          }
        },
        {
          title: '电池序列号',
          dataIndex: 'batterySN',
          width: 150,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '类型区分',
          dataIndex: 'ALLOCATE_TYPE',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [
            { text: '借出出库', value: '82121003' },
            { text: '还出出库', value: '82121004' }
          ],
          dictItems: [
            { text: '借出出库', value: '82121003' },
            { text: '还出出库', value: '82121004' }
          ]
        }
      ];
    },
    // 获取所有人的信息
    async getDealerUser() {
      const res = await getDealerUser();
      this.cunUserList = res.data;
    },
    // 获取税率
    async findAllRepair() {
      let re = await findAllRepair();
      this.tax = re.data['1003'];
    },
    // 打印的方法
    async handlePrint() {
      // 打印数据
      const res = await printData(this.cunId);
      this.cunPrintlist = res.data;
      this.dy = true;
      this.SalesprintList = this.cunPrintlist;
      this.cunUserList.forEach(x => {
        if (this.SalesprintList.baseInfo.USER_ID == x.userId) {
          this.SalesprintList.baseInfo.USER_NAME = x.employeeName;
        }
        if (this.SalesprintList.baseInfo.HANDLER == x.userId) {
          this.SalesprintList.baseInfo.HANDLER_NAME = x.employeeName;
        }
      });
      let type = this.SalesprintList.baseInfo.ALLOCATE_TYPE == '82121003' ? '借出出库' : '还出出库';
      this.SalesprintList.baseInfo.STOCK_OUT_TYPE = type ? type : '借出出库';
      // 打印
      this.$nextTick(() => {
        this.$refs.print.EXCUTE_PRINT();
      });
    },
    async getSrorageList() {
      this.columns.find(item => item.dataIndex == 'STORAGE_CODE').filterItems = this.columns.find(item => item.dataIndex == 'STORAGE_CODE').editItems = (await getStorageList({})).data.map(x => ({
        text: x.STORAGE_NAME,
        value: x.STORAGE_CODE
      }));
    },
    selectTableFun(val) {
      this.selectRow = val;
    },
    // 检测table数据变化
    handleTableDataUpdate(e) {
      this.tableDataBackUp = e;
      this.inTableListData = e;
    },
    // 获取打印的信息
    async printData() {
      const res = await printData(this.cunId);
      this.cunPrintlist = res.data;
    },
    // 根据借出出库单号查询主表数据
    async getMainTableList() {
      let params = {};
      if (this.form.find(item => item.fieldName == 'adjustOutboundNo').initialValue) {
        params.adjustOutboundNo = this.form.find(item => item.fieldName == 'adjustOutboundNo').initialValue;
      } else {
        params = this.$refs.form.SUBMIT_FORM();
      }
      try {
        this.$refs.table.START_LOADING();
        let res = await queryMainTableByNo(params.adjustOutboundNo);
        this.$refs.table.STOP_LOADING();
        this.tableDataList = res.data;
        // 查询后,类型区分禁止选择
        this.form.find(item => item.fieldName == 'allocateType').disabled = true;
        // 如果已入账 禁用按钮
        if (res.data && res.data[0].IS_FINISHED == '10041001') {
          // 禁止
          this.form.find(item => item.fieldName == 'allocateInNo').disabled = true;
          this.buildBtn = true;
        }
      } catch (err) {
        console.log(err);
        this.$refs.table.STOP_LOADING();
      }
    },
    // 单号选择点击确定
    handleOrderSelectConfirm(e) {
      console.log(e);
      this.form.find(item => item.fieldName == 'remark').initialValue = e[0].REMARK;
      this.form.find(item => item.fieldName == 'outBoundDate').initialValue = moment(e[0].CREATED_AT).format('YYYY-MM-DD');
      this.form.find(item => item.fieldName == 'customerCode').initialValue = e[0].CUSTOMER_CODE;
      this.form.find(item => item.fieldName == 'customerName').initialValue = e[0].CUSTOMER_NAME;
      this.form.find(item => item.fieldName == 'adjustOutboundNo').initialValue = e[0].ALLOCATE_OUT_NO;
      this.form.find(item => item.fieldName == 'allocateInNo').initialValue = e[0].ALLOCATE_IN_NO;
      this.form.find(item => item.fieldName == 'allocateType').initialValue = e[0].ALLOCATE_TYPE;
      this.form.find(item => item.fieldName == 'allocateInNo').disabled = true;
      this.cunId = e[0].ALLOCATE_OUT_ID;
      console.log(this.cunId, 'e[0].ALLOCATE_OUT_ID');
      this.cancelBtn = false; // 取消
      this.addBtn = false; // 新增
      this.buildBtn = true; // 新增
      this.saveBtn = true; // 保存
      this.zuofeiBtn = false; // 作废
      this.chukuBtn = false; // 出库
      this.printBtn = true; // 打印
      this.getMainTableList();
    },
    // 点击新建按钮
    newBuild() {
      this.$refs.form.RESET_FORM();
      this.form.find(item => item.fieldName == 'adjustOutboundNo').disabled = true;
      this.form.find(item => item.fieldName == 'customerCode').disabled = false;
      this.form.find(item => item.fieldName == 'allocateType').disabled = false;
      this.form.find(item => item.fieldName == 'outBoundDate').initialValue = moment().format('YYYY-MM-DD');
      this.tableDataList = [];
      this.cancelBtn = false; // 取消
      this.addBtn = false; // 新增 xia
      this.buildBtn = true; // 新增 shang
      this.saveBtn = true; // 保存
      this.zuofeiBtn = true; // 作废
      this.chukuBtn = true; // 出库
      this.printBtn = true; // 打印 原 true
      this.isFinished = false;
    },
    // 点击新增按钮
    addHandle() {
      this.adjustOrderAddEditMode = false;
      this.editData = {};
      if (!this.form.find(item => item.fieldName == 'customerCode').initialValue) {
        return this.$notify.warning({ title: '提示信息', message: '请先填写' + this.form[1].label });
      }
      this.visibleAdjustOrderAdd = true;
    },
    // 配件新增点击确定
    handlePartAddConfirm(val) {
      console.log(val);
      // partNo配on件代码  storageCode仓库
      let pd = false;
      this.tableDataList.forEach(x => {
        let pdpartNo = false;
        let pdstorageCode = false;
        if (val.PART_NO == x.PART_NO) {
          pdpartNo = true;
        }
        if (val.STORAGE_CODE == x.STORAGE_CODE) {
          pdstorageCode = true;
        }
        if (pdstorageCode && pdpartNo) {
          pd = true;
        }
      });
      if (pd) {
        this.$notify({
          title: '提示',
          message: '请勿重复添加配件',
          type: 'warning'
        });
        return;
      }
      if (val.OUT_QUANTITY == 0) {
        val.OUT_QUANTITY = 1;
        val.OUT_AMOUNT = Number(val.priceCoefficient) * Number(val.OUT_PRICE) * Number(val.OUT_QUANTITY);
      }
      // this.visibleAdjustOrderAdd = false;
      this.saveBtn = false;
      // 保存为fasle
      this.saveBtn = false;
      this.chukuBtn = true;
      this.tableDataList = this.tableDataList.concat(val);
      this.form.find(item => item.fieldName == 'allocateType').disabled = true;
      notifyAction('保存成功！');
    },
    handlePartAddConfirmEdit(val) {
      this.tableDataList[val.$index] = val;
      this.saveBtn = false;
      this.chukuBtn = true;
    },
    // 导出
    importFun() {
      partAllocateOutExportExcel(this.form.find(item => item.fieldName == 'adjustOutboundNo').initialValue).then(res => {
        console.log(res);
        exportExcelFile(res, '配件调拨出库');
      });
    },
    delete() {},
    // 新建出库单保存
    async save() {
      let stockOutDate = formatdate(new Date());
      let outAmountTotal = 0,
        costAmountTotal = 0; // 合计金额，合计成本金额
      let topFormData = await this.$refs.form.GET_FORM_DATA();

      let submitTableData = JSON.parse(JSON.stringify(this.tableDataBackUp));
      // console.log(this.tableDataBackUp, '表单数据');
      // 判断是否已入账
      if (submitTableData && submitTableData[0] && submitTableData[0].IS_FINISHED && submitTableData[0].IS_FINISHED == '10041001') {
        this.$notify({
          title: '提示',
          message: '该单号已入账',
          type: 'warning'
        });
      }
      if (this.tableDataBackUp == null || this.tableDataBackUp.length == 0 || this.tableDataBackUp == undefined) {
        this.$notify({
          title: '提示',
          message: '不可以保存空单据，请添加配件！',
          type: 'warning'
        });
        return;
      }
      jsonToHump(submitTableData);
      submitTableData.map(item => {
        if (item.itemId == '' || item.itemId == null || item.itemId == undefined) {
          item.itemId = 'N';
          item.flag = 'A';
        }
        item.costPrice = (item.outPrice / (1 + (+this.tax || 0.13))).toFixed(2); // 不含税成本单价
        // item.flag= 'X';    //修改时添加 itemID 有不用携带
      });
      let id = '';
      if (this.shanchu.length > 0) {
        id = this.shanchu.join(',');
      }
      try {
        let res = await saveOutboundOrderCreate({
          dms_table: submitTableData,
          stockOutDate,
          items: id,
          remark: this.form.find(item => item.fieldName == 'remark').initialValue,
          customerCode: topFormData[1].customerCode,
          customerName: topFormData[1].customerName,
          ptype: this.ptype ? this.ptype : null, // 模块区分
          allocateType: this.form.find(x => x.fieldName == 'allocateType').initialValue,
          allocateInNo: this.form.find(x => x.fieldName == 'allocateInNo').initialValue
        });
        if (res.resultCode == 200) {
          this.$notify.success({ title: '提示信息', message: '保存成功' });
          this.form.find(item => item.fieldName == 'adjustOutboundNo').disabled = true;
          this.form.find(item => item.fieldName == 'customerCode').disabled = true;
          this.cancelBtn = false; // 取消
          this.addBtn = false; // 新增
          this.buildBtn = true; // 新增
          this.saveBtn = true; // 保存
          this.zuofeiBtn = false; // 作废
          this.chukuBtn = false; // 出库
          this.printBtn = true; // 打印
          this.form.find(item => item.fieldName == 'adjustOutboundNo').initialValue = res.data;
          this.shanchu = [];
          this.$nextTick(() => {
            this.getMainTableList();
          });
          this.searchAdjustOrder();
        }
      } catch (err) {
        console.log(err);
      }
    },
    async searchAdjustOrder() {
      const res = await searchAdjustOrder({ allocateOutNo: this.form.find(item => item.fieldName == 'adjustOutboundNo').initialValue });
      this.cunId = res.data.rows[0].ALLOCATE_OUT_ID;
    },
    // 出库单入账操作
    async out() {
      let formParams = await this.$refs.form.GET_FORM_DATA();
      // console.log(formParams[1].adjustOutboundNo);
      if (this.outBtnLoading) return;
      this.outBtnLoading = true;
      console.log(this.tableDataBackUp, '----------tableDataBackUp--------------');
      let flag = false;
      this.tableDataBackUp.forEach(x => {
        if (x.OUT_PRICE < x.COST_PRICE) {
          flag = true;
          return;
        }
      });
      let res = {};
      try {
        if (flag) {
          if (isAuthorized('1313', '13131008')) {
            res = await outBoundOrderRecorded(formParams[1].adjustOutboundNo);
            this.outBtnLoading = false;
          } else {
            this.$notify({
              title: '警告',
              message: '出库单价小于成本价，您无出库权限！',
              type: 'warning'
            });
          }
        } else {
          res = await outBoundOrderRecorded(formParams[1].adjustOutboundNo);
          this.outBtnLoading = false;
        }
        if (res.resultCode == 200) {
          notifyAction('出库成功！');
          this.cancelBtn = false; // 取消
          this.addBtn = true; // 新增
          this.buildBtn = false; // 新增
          this.saveBtn = true; // 保存
          this.zuofeiBtn = true; // 作废
          this.chukuBtn = true; // 出库
          this.printBtn = false; // 打印
          this.form.find(item => item.fieldName == 'customerCode').disabled = true;
          this.form.find(item => item.fieldName == 'adjustOutboundNo').disabled = true;
          this.exportBtn = false;
          this.isFinished = true;
        }
      } catch (err) {
        this.outBtnLoading = false;
        console.log(err);
      }
    },
    // 出库单作废
    async quit() {
      let formParams = await this.$refs.form.GET_FORM_DATA();
      if (this.quitBtnLoading) return;
      try {
        this.quitBtnLoading = true;
        let res = await outBoundOrderDelete(formParams[1].adjustOutboundNo);
        this.quitBtnLoading = false;
        if (res.resultCode == 200) {
          notifyAction('出库单已作废！');
          this.$refs.form.RESET_FORM();
          this.cancelBtn = true; // 取消
          this.addBtn = true; // 新增
          this.buildBtn = false; // 新增
          this.saveBtn = true; // 保存
          this.zuofeiBtn = true; // 作废
          this.chukuBtn = true; // 出库
          this.printBtn = true; // 打印
          this.form.find(item => item.fieldName == 'customerCode').disabled = true;
          this.form.find(item => item.fieldName == 'adjustOutboundNo').disabled = false;
          // this.exportBtn = false;
          this.tableDataList = [];
        }
      } catch (err) {
        this.quitBtnLoading = false;
        console.log(err);
      }
    },
    cancel() {
      this.shanchu = [];
      this.tableDataList = [];
      this.$refs.form.RESET_FORM();
      this.form.find(item => item.fieldName == 'adjustOutboundNo').disabled = false;
      this.form.find(item => item.fieldName == 'customerCode').disabled = true;
      this.form.find(item => item.fieldName == 'allocateType').disabled = true;
      this.cancelBtn = true;
      this.addBtn = true;
      this.buildBtn = false;
      this.saveBtn = true;
      this.zuofeiBtn = true;
      this.chukuBtn = true;
      this.printBtn = true;
      this.isFinished = false;
      this.exportBtn = true;
    },
    print() {},
    // collapseHandle(){}
    changeHandle(val) {
      console.log('表单面板数据：', val);
    },

    // 借出出库单号查询
    adjustOutbound() {
      this.orderList = this.form.find(x => x.fieldName == 'adjustOutboundNo').initialValue;
      console.log(this.orderList, 'this.orderList111');
      this.visibleAdjustOrder = true;
    },
    // 客户选择
    order() {
      this.visibleCustomerChoice = true;
    },
    // 客户选择点击确定
    handleCustomerChoiceConfirm(e) {
      this.customerPriceRate = e[0].PRICE_RATE;
      this.form.find(item => item.fieldName == 'customerCode').initialValue = e[0].CUSTOMER_CODE;
      this.form.find(item => item.fieldName == 'customerName').initialValue = e[0].CUSTOMER_NAME;
      this.visibleCustomerChoice = false;
    },
    // 行数据点击删除
    handleDelete() {
      console.log(this.selectRow);
      if (!this.isFinished) {
        let rowData = this.selectRow[0];
        confirmAction('将要删除本条配件信息，是否继续？')
          .then(res => {
            this.$refs.table.EXECUTE_DELETE([rowData]);
            if (rowData.ITEM_ID) {
              this.shanchu.push(rowData.ITEM_ID);
            }
            this.saveBtn = false;
            this.chukuBtn = true;
          })
          .catch(err => {});
      } else {
        this.$notify.error({ title: '提示信息', message: '该单号已出库，无法删除配件!' });
      }
    },
    // 行数据点击编辑
    editHandle(e) {
      // console.log(e);
      this.editData = e;
      this.BILL_NO = this.form.find(item => item.fieldName == 'allocateInNo').initialValue;
      console.log(this.BILL_NO, 12321);

      this.adjustOrderAddEditMode = true;
      this.visibleAdjustOrderAdd = true;
    },
    // 查询打印参数
    async queryPrintParams() {
      let res = await dealerPrintApi({
        vModule: '90211009',
        vNormalCode: 'BJJC'
      });
      if (res.resultCode == 200 && res.data.length) {
        this.printParams = res.data[0];
        this.printParams.vDirectPrint = this.printParams.vDirectPrint === 0 ? '0' : this.printParams.vDirectPrin;
      }
      console.log(this.printParams, '打印参数');
    }
  }
};
</script>

<style scoped lang="less"></style>
